<template>
	<view class="product-order-payment">
		<view class="order-info">
			<view class="order-header">
				<text class="order-title">订单信息</text>
			</view>
			<view class="order-details">
				<view class="detail-item">
					<text class="label">订单号:</text>
					<text class="value">{{ order.orderNo }}</text>
				</view>
				<view class="detail-item">
					<text class="label">支付金额:</text>
					<text class="value price">¥{{ order.payAmount }}</text>
				</view>
				<view class="detail-item">
					<text class="label">订单状态:</text>
					<text class="value status" :class="statusClass">{{ statusText }}</text>
				</view>
			</view>
		</view>
		
		<view class="payment-status" v-if="paymentStatus">
			<view class="status-header">
				<text class="status-title">支付状态</text>
			</view>
			<view class="status-content">
				<text class="status-text">{{ paymentStatusText || '未查询' }}</text>
				<view v-if="isPolling" class="polling-indicator">
					<text class="loading-text">正在查询支付状态...</text>
				</view>
			</view>
		</view>
		
		<view class="payment-actions">
			<button 
				@click="handlePay" 
				:disabled="isPaying || isPolling || order.status === 'paid'"
				class="pay-button"
				:class="{ disabled: isPaying || isPolling || order.status === 'paid' }"
			>
				{{ buttonText }}
			</button>
			
			<button 
				v-if="order.status === 'pending' && !isPaying && !isPolling"
				@click="handleCancelOrder" 
				class="cancel-button"
			>
				取消订单
			</button>
		</view>
	</view>
</template>

<script>
import ProductOrderPayment from '@/utils/ProductOrderPayment.js';
import { cancelProductOrder } from '@/api/productOrder.js';

export default {
	name: 'ProductOrderPayment',
	props: {
		order: {
			type: Object,
			required: true
		}
	},
	data() {
		return {
			paymentHandler: new ProductOrderPayment(),
			isPaying: false,
			isPolling: false,
			paymentStatus: null
		};
	},
	computed: {
		statusText() {
			const statusMap = {
				'pending': '待支付',
				'paid': '已支付',
				'shipped': '已发货',
				'delivered': '已送达',
				'completed': '已完成',
				'cancelled': '已取消'
			};
			return statusMap[this.order.status] || this.order.status;
		},

		statusClass() {
			const classMap = {
				'pending': 'status-pending',
				'paid': 'status-paid',
				'shipped': 'status-shipped',
				'delivered': 'status-delivered',
				'completed': 'status-completed',
				'cancelled': 'status-cancelled'
			};
			return classMap[this.order.status] || '';
		},

		paymentStatusText() {
			if (!this.paymentStatus) return '';
			
			const statusMap = {
				'SUCCESS': '支付成功',
				'NOTPAY': '未支付',
				'CLOSED': '已关闭',
				'REFUND': '已退款',
				'USERPAYING': '用户支付中',
				'PAYERROR': '支付失败'
			};
			
			return statusMap[this.paymentStatus] || this.paymentStatus;
		},

		buttonText() {
			if (this.isPaying) return '支付中...';
			if (this.isPolling) return '查询中...';
			if (this.order.status === 'paid') return '已支付';
			return '立即支付';
		}
		},
	methods: {

		/**
		 * 处理支付
		 */
		async handlePay() {
			try {
				this.isPaying = true;
				
				// 获取用户openid
				const openid = this.paymentHandler.getUserOpenid();
				
				// 发起支付
				const wxPayParams = await this.paymentHandler.initiatePayment(
					this.order._id, 
					openid
				);
				
				// 调起微信支付
				await this.callWechatPay(wxPayParams);
				
				// 开始查询支付状态
				this.startPaymentStatusQuery();
				
			} catch (error) {
				console.error('支付失败:', error);
				uni.showToast({
					title: '支付失败: ' + error.message,
					icon: 'none'
				});
			} finally {
				this.isPaying = false;
			}
		},

		/**
		 * 调起微信支付
		 */
		callWechatPay(wxPayParams) {
			return new Promise((resolve, reject) => {
				wx.requestPayment({
					...wxPayParams,
					success: () => {
						resolve();
					},
					fail: (err) => {
				
						reject(new Error('支付失败'));
					}
				});
			});
		},

		/**
		 * 开始查询支付状态
		 */
		startPaymentStatusQuery() {
			this.isPolling = true;
			
			this.paymentHandler.handlePaymentComplete(
				this.order._id,
				// 支付成功回调
				(orderId, result) => {
					this.isPolling = false;
					this.paymentStatus = result.wechatTradeState;
					uni.showToast({
						title: '支付成功！',
						icon: 'success'
					});
					
					// 通知父组件支付成功
					this.$emit('payment-success', { orderId, result });
				},
				// 支付失败回调
				(orderId, error) => {
					this.isPolling = false;
					uni.showToast({
						title: '支付失败: ' + error.message,
						icon: 'none'
					});
					
					// 通知父组件支付失败
					this.$emit('payment-error', { orderId, error });
				},
				// 支付超时回调
				(orderId) => {
					this.isPolling = false;
					uni.showToast({
						title: '支付状态查询超时，请稍后手动检查',
						icon: 'none'
					});
					
					// 通知父组件支付超时
					this.$emit('payment-timeout', { orderId });
				}
			);
		},

		/**
		 * 取消订单
		 */
		async handleCancelOrder() {
			try {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消这个订单吗？',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '取消中...'
							});
							
							await cancelProductOrder(this.order._id, '用户主动取消');
							
							uni.hideLoading();
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							});
							
							// 通知父组件订单取消
							this.$emit('order-cancelled', { orderId: this.order._id });
						}
					}
				});
			} catch (error) {
				console.error('取消订单失败:', error);
				uni.hideLoading();
				uni.showToast({
					title: '取消订单失败',
					icon: 'error'
				});
			}
		}
	},
	
	beforeDestroy() {
		// 组件销毁时停止轮询
		if (this.paymentHandler) {
			this.paymentHandler.pollingIntervals.forEach((interval, orderId) => {
				this.paymentHandler.stopPolling(orderId);
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.product-order-payment {
	padding: 20rpx;
	background-color: #fff;
	border-radius: 16rpx;
	margin: 20rpx;
}

.order-info {
	margin-bottom: 30rpx;
	
	.order-header {
		margin-bottom: 20rpx;
		
		.order-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.order-details {
		.detail-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;
			
			.label {
				font-size: 28rpx;
				color: #666;
			}
			
			.value {
				font-size: 28rpx;
				color: #333;
				
				&.price {
					color: #ff4757;
					font-weight: bold;
				}
				
				&.status {
					&.status-pending {
						color: #ffa502;
					}
					
					&.status-paid {
						color: #2ed573;
					}
					
					&.status-shipped {
						color: #3742fa;
					}
					
					&.status-delivered {
						color: #2ed573;
					}
					
					&.status-completed {
						color: #2ed573;
					}
					
					&.status-cancelled {
						color: #ff4757;
					}
				}
			}
		}
	}
}

.payment-status {
	margin-bottom: 30rpx;
	padding: 20rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
	
	.status-header {
		margin-bottom: 16rpx;
		
		.status-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.status-content {
		.status-text {
			font-size: 26rpx;
			color: #666;
		}
		
		.polling-indicator {
			margin-top: 10rpx;
			
			.loading-text {
				font-size: 24rpx;
				color: #1890ff;
			}
		}
	}
}

.payment-actions {
	display: flex;
	gap: 20rpx;
	
	.pay-button {
		flex: 1;
		height: 80rpx;
		background-color: #1890ff;
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: bold;
		
		&.disabled {
			background-color: #ccc;
			cursor: not-allowed;
		}
	}
	
	.cancel-button {
		flex: 1;
		height: 80rpx;
		background-color: #fff;
		color: #666;
		border: 2rpx solid #ddd;
		border-radius: 12rpx;
		font-size: 28rpx;
	}
}
</style> 